package com.xuesi.demoadmin.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageInfo;
import com.xuesi.demoadmin.annotation.Auth;
import com.xuesi.demoadmin.annotation.Permission;
import com.xuesi.demoadmin.entity.R;
import com.xuesi.demoadmin.entity.Article;
import com.xuesi.demoadmin.entity.ArticleDetail;
import com.xuesi.demoadmin.service.IArticleService;
import com.xuesi.demoadmin.utils.PageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    @Autowired
    private IArticleService articleService;

    @SuppressWarnings("unchecked")
    @Auth
    @Permission
    @GetMapping("/list")
    public R<Map<String, Object>> list(@RequestBody Article article) {
        // 设置请求分页数据
        try {
            PageUtils.startPage();
        } catch (Exception e) {
            return null;
        }

        List<Article> list = this.articleService.selectArticleList(article);

        Map<String, Object> result = new HashMap<>();

        result.put("count", new PageInfo(list).getTotal());
        result.put("list", list);

        return new R<Map<String, Object>>(200, "success", result);
    }

    @Auth
    @Permission
    @PostMapping("/add")
    public R<Object> add(@Validated @RequestBody Article article) {
        Date now = new Date();
        article.setCreatedAt(now);
        article.setUpdatedAt(now);
        this.articleService.insertArticle(article);
        return new R<Object>(200, "success");
    }

    @Auth
    @Permission
    @GetMapping("/detail")
    public R<Object> detail(@RequestBody ArticleDetail articleDetail) {
        Long articleId = articleDetail.getArticleId();
        Article article = this.articleService.selectArticleById(articleId);
        if (article == null) {
            return new R<Object>(400, "文章id不合法");
        }
        return new R<Object>(200, "success", article);
    }

    @Auth
    @Permission
    @PostMapping("/delete")
    public R<Object> delete(@RequestBody ArticleDetail articleDetail) {
        Long articleId = articleDetail.getArticleId();
        Article article = new Article();
        article.setArticleId(articleId);
        Date now = new Date();
        article.setDeletedAt(now);
        article.setUpdatedAt(now);
        this.articleService.deleteArticleById(article);
        return new R<Object>(200, "success", article);
    }
}
